package cn.qu.dockman.protocol.def;

import cn.qu.dockman.protocol.command.Command;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zh on 17/3/11.
 */
public class CommandFactory {

    private final static Logger logger = LoggerFactory.getLogger(CommandFactory.class);

    private CommandFactory() {
    }

    public static Command getCommand(String json) {
        HashMap map = new Gson().fromJson(json, HashMap.class);
        Map header = (Map) map.get("header");
        String headerName = (String) header.get("name");
        char fi = headerName.charAt(0);
        String name = headerName.replaceFirst(Character.toString(fi), Character.toString(Character.toUpperCase(fi))) + "Command";

        Class<? extends Command> commandClass = findClass(name);

        if (commandClass != null) {
            return new Gson().fromJson(json, commandClass);
        } else {
            return null;
        }
    }

    private static Class<? extends Command> findClass(String className) {
        try {
            return (Class<? extends Command>) Class.forName("cn.qu.dockman.protocol.command.client." + className);
        } catch (ClassNotFoundException e) {
            try {
                return (Class<? extends Command>) Class.forName("cn.qu.dockman.protocol.command.server." + className);
            } catch (ClassNotFoundException e1) {
                logger.error("未找到命令定义");
                return null;
            }
        }
    }

}
